package com.zhiban.project.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import dinamica.Db;
import dinamica.GenericTableManager;
import dinamica.Recordset;
import dinamica.RecordsetException;

/**
 * 试卷自动组卷
 * 
 * @author lxp
 *
 */
public class AuthSaveController extends GenericTableManager {

	public int service(Recordset inputParams) throws Throwable {
		super.service(inputParams);
		HttpServletRequest request = getRequest();
		String entity_ids[] = request.getParameterValues("entity_id");
		String role_id = request.getParameter("role_id");
		List questionDataList = new ArrayList();
		if (entity_ids != null)
			for (String ids : entity_ids) {
				Map<String, Object> paraMap = new HashMap<String, Object>();
				String idsArr[] = ids.split("#");
				paraMap.put("entity_id", Integer.parseInt(idsArr[0]));
				paraMap.put("entity_type", Integer.parseInt(idsArr[1]));
				questionDataList.add(paraMap);
			}
		addAuthList(questionDataList, Integer.parseInt(role_id));
		int rc = 0;
		return rc;
	}

	private void addAuthList(List<Map<String, Object>> questionDataList,
			Integer role_id) throws Throwable {
		Db db = getDb();
		Recordset detail = new Recordset();
		String insertSql = getSQL(getResource("insert.sql"), detail);
		detail.append("entity_id", java.sql.Types.INTEGER);
		detail.append("entity_type", java.sql.Types.INTEGER);
		detail.append("role_id", java.sql.Types.INTEGER);
		for (Map<String, Object> questionData : questionDataList) {
			detail.addNew();
			addQuestion(db, insertSql, detail, questionData, role_id);
			String cmd = getSQL(insertSql, detail);
			db.addBatchCommand(cmd);
		}
		db.exec();
	}

	private void addQuestion(Db db, String sql, Recordset detail,
			Map<String, Object> question, Integer role_id)
			throws RecordsetException {
		detail.setValue("entity_id", question.get("entity_id"));
		detail.setValue("entity_type", question.get("entity_type"));
		detail.setValue("role_id", role_id);
	}

}
